package com.tcpclient;


import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class TcpClient2 {


    public static void main(String[] args) {
        tcpsend();
    }

    public static void tcpsend() {

        int port = 1024;
        String ip = "127.0.0.1";
        String data =  "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Msg><MESSAGE>************</MESSAGE></Msg>";
        sendtcp(port, ip, data);
    }

    private static void sendtcp(int port, String ip, String data) {
        int timeout = 700000;
        OutputStream output = null;
        String recvStr = null;
        InputStream input = null;
        int headLength = 8;
        String charset = StandardCharsets.UTF_8.name();
        Socket socket = null;
        try {
            socket = new Socket(ip, port);
            socket.setSoTimeout(timeout);
            output = socket.getOutputStream();

            StringBuilder outLength = new StringBuilder();
            int datalen = data.getBytes(StandardCharsets.UTF_8).length;
            outLength.append(StringUtils.leftPad(String.valueOf(datalen), headLength, "0"));
            byte[] outData = new byte[headLength + datalen];
            System.arraycopy(outLength.toString().getBytes(), 0, outData, 0, headLength);
            System.arraycopy(data.getBytes(StandardCharsets.UTF_8), 0, outData, headLength, datalen);
            System.out.println("写出的数据" + new String(outData, charset));
            output.write(outData);
            output.flush();
            input = socket.getInputStream();

            byte[] headBuffer = new byte[headLength];
            for (int offset = 0; offset < headLength; ) {
                int length = input.read(headBuffer, offset, headLength - offset);
                if (length < 0) {
                    throw new RuntimeException("invalid_packet_head");
                }
                offset += length;
            }
            int totalLength = Integer.parseInt(new String(headBuffer, charset));
            byte[] resultBuffer = new byte[totalLength];
            int offset = 0;
            while (offset < totalLength) {
                int realLength = input.read(resultBuffer, offset, totalLength - offset);
                if (realLength >= 0) {
                    offset += realLength;
                } else {
                    System.out.println("the length of packet should be :" + totalLength + " but encounter eof at offset:" + offset);
                    throw new RuntimeException("报文头读取异常");
                }
            }
            recvStr = new String(resultBuffer, charset);

            System.out.println("收到报文：[" + recvStr + "]");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            try {
                if (socket != null) {
                    socket.close();
                }
                if (output != null) {
                    output.close();
                }
                if (input != null) {
                    input.close();
                }
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
    }
}
